<?php

namespace app\modules\admini\components;

use Yii;
use yii\web\Controller;
use app\modules\admini\models\AdminLogger;
use app\modules\admini\models\Config;
use app\modules\admini\models\Upload;
use app\modules\admini\components\BUtils;
use app\modules\admini\components\BUpload;

/**
 * Default controller for the `admini` module
 */
class BController extends Controller
{
	public $layout = false;
    public $_uniqid;
    public $_baseUrl;

    public function init()
    {
        parent::init();
        $this->_uniqid = BUtils::guid();
        $this->_baseUrl = Yii::$app->request->getHostInfo().Yii::$app->getHomeUrl();
        //Yii::$app->setHomeUrl($this->_baseUrl);
        //$this->output(Config::get('page_size'));
    }
    
    /**
     * 用户登录检查，功能操作权限检查
     */
    public function beforeAction($action){
        //登录检查
        if (Yii::$app->user->isGuest) {
            if($this->id == 'default')
                return $this->redirect(['/admini/public/login'])->send();
            else
                $this->callback([],'timeout');
        }

        $rotue = $this->id.'/'.$this->action->id;

        //lookup 查找带回排除
        if($this->action->id == 'lookup'){
            return true;
        }

        //get 前缀排除
        $prefix = explode('-',$this->action->id);
        $prefix = $prefix[0];
        if($prefix == 'get'){
            return true;
        }
        
        
        //自定义排除
		$default = array(
            'default/index',//首页
			'default/desktop',//首页
            'user/user-info',//查看个人账户
            'user/user-update',//修改个人账户
            'user/user-update-password',//修改密码

            //lookup search action
            //...................
		);

		$_acl = Yii::$app->session->get('_acl');
		$_acl = explode(',',$_acl['acl']);
		$_acl = array_merge($_acl,$default);
		
		if(Yii::$app->user->identity->group_id != 1  && !in_array($rotue,$_acl)){
			$this->callback(['message'=>'无操作权限！'],'error');
		}
        return true;
    }

    //获取行数据权限
    public function getRowAcl(){
        if(Yii::$app->user->identity->group_id != 1  && !in_array($this->id.'/'.'all',$_acl)){
            if(!in_array($this->id.'/'.'group',$_acl)){
                return 'oneself';
            }else{
                return 'group';
            }
        }else{
            return 'all';
        }
       
    }

     //获取列数据权限
    public function getColumnAcl($column){
        if(Yii::$app->user->identity->group_id != 1  && !in_array($this->id.'/'.$column,$_acl)){
           return false;
        }else{
            return true;
        }
       
    }

    public function actionUpload()
    {
        if (Yii::$app->request->getIsPost() && isset($_FILES['file'])) {
            try {
                $file = BUpload::upload($_FILES['file']);
                if (is_array($file)) {
                    $model = new Upload();
                    $model->user_id = Yii::$app->user->identity->id;
                    $model->file_name = $file['pathname'];
                    $model->thumb_name = $file['paththumbname'];
                    $model->real_name = $file['name'];
                    $model->file_ext = $file['extension'];
                    $model->file_mime = $file['type'];
                    $model->file_size = $file['size'];
                    $model->save_path = $file['savepath'];
                    $model->hash = $file['hash'];
                    $model->save_name = $file['savename'];
                    if ($model->save()) {
                        exit(json_encode(array(
                            'statusCode' => 200,
                            'message'=>'上传成功',
                            'filename' => $this->_baseUrl . '/' . $file['pathname']
                        )));
                    } else {
                        @unlink($file['pathname']);
                        @unlink($file['paththumbname']);
                        exit(json_encode(array(
                            'statusCode' => 300,
                            'message'=>'上传错误',
                        )));
                    }
                } else {
                    exit(json_encode(array(
                        'statusCode' => 300,
                        'message' => '上传错误，请检查网站的上传设置中是否允许该类型的文件'
                    )));
                }
            } catch(Exception $ex) {
                exit(json_encode(array(
                    'statusCode' => 300,
                    'message' => $ex->getMessage(),
                )));
            }
            
        } 
    }

    public function output($var){
        echo '<div class="bjui-pageContent" style=""><pre>';
        var_dump($var);
        echo '</pre></div>';
        exit();
    }
    /**
     * 创建url
     */
    public  function createUrl($param){

        return BUtils::createUrl($param);
    }

    /**
     * BJUI回调
     */
	public  function callback($json=array(), $status='ok')
    {
        $config = array(
            'ok'=>array(200, '操作成功'), 
            'error'=>array(300, '操作失败'), 
            'timeout'=>array(301, '操作超时'),
        );
        $json['statusCode'] = $config[$status][0];
        !isset($json['message']) && $json['message'] = $config[$status][1];

        echo json_encode($json);
        Yii::$app->end();
    }

    /**
     * 解析验证error信息
     */
    public function getErrorMessage($error){
        $msgStr = '<strong>以下表单填写有误:</strong><br>';
        foreach ($error as $key => $value) {
            foreach ($value as $k => $v) {
               $msgStr .= '<p>'.$v.'</p>';
            }
        }
        return $msgStr;
    }

    /**
     * 后台日志记录
     * @param  $intro
     */
    protected function _adminiLogger(array $arr = array()) {
        $admin_logger = Config::get('admin_logger');
        if ($admin_logger == 'open') {
            $model = new AdminLogger();
            $model->setAttributes($arr);
            !isset($arr['user_id']) && $model->user_id = Yii::$app->user->identity->id;
            !isset($arr['user_name']) && $model->user_name = Yii::$app->user->identity->username;
            $model->url = Yii::$app->request->getUrl();
            $model->ip = BUtils::getClientIP();
            $model->save();
        }
    }

    /**
     * 全局分页条数定义
     */
    public  function loadPageOption(){
        return array(
            '20'=>20,
            '30'=>30,
            '50'=>50,
            '100'=>100,
            '200'=>200,
        );
    }

    /**
     * 全局分页条数下拉框html定义
     */
    public  function loadPageOptionHtml(){
        return '<option value="20">20</option><option value="30">30</option><option value="50">50</option><option value="100">100</option><option value="200">200</option>';
    }

    public function getSheetNumber($prefix='',$num,$suffix=''){
    	$cmd = Yii::$app->db->createCommand("call generate_orderNo(:prefix,:num,@res)");
        $cmd->bindParam(':prefix',$prefix,\PDO::PARAM_STR,50);
        $cmd->bindParam(':num',$num,\PDO::PARAM_STR,50);
        $res = $cmd->queryOne();
       
        return $res['newOrderNo'].$suffix;
    }
}
